<template>
    <div class="attendance-container">
      <!-- 统计信息卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-value">{{ stats.normalDays }}</div>
              <div class="stat-label">正常出勤</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-value">{{ stats.lateTimes }}</div>
              <div class="stat-label">迟到次数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-value">{{ stats.earlyTimes }}</div>
              <div class="stat-label">早退次数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-value">{{ stats.absentDays }}</div>
              <div class="stat-label">异常天数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
  
      <!-- 搜索区域 -->
      <el-card shadow="never" class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="searchForm.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="searchForm.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 打卡按钮区域 -->
      <div class="clock-buttons">
        <el-button 
          type="primary" 
          @click="handleClockIn('am')" 
          :disabled="hasClockedInAM"
        >
          上班打卡
        </el-button>
        <el-button 
          type="success" 
          @click="handleClockIn('pm')" 
          :disabled="hasClockedInPM"
        >
          下班打卡
        </el-button>
      </div>
  
      <!-- 打卡记录表格 -->
      <el-card shadow="never" class="table-card">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" type="index"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="am" label="上午打卡时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.am || '未打卡' }}
            </template>
          </el-table-column>
          <el-table-column prop="pm" label="下午打卡时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.pm || '未打卡' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ scope.row.status || '未完成打卡' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          class="pagination"
        ></el-pagination>
      </el-card>
    </div>
  </template>
  
  <script>
  import { clockIn, getClockList, getClockHistory } from '@/api/clock'
  
  export default {
    name: 'Attendance',
    data() {
      return {
        stats: {
          normalDays: 0,
          lateTimes: 0,
          earlyTimes: 0,
          absentDays: 0
        },
        searchForm: {
          startDate: '',
          endDate: ''
        },
        tableData: [],
        loading: false,
        pagination: {
          currentPage: 1,
          pageSize: 5,
          total: 0
        },
        hasClockedInAM: false,
        hasClockedInPM: false
      }
    },
    created() {
      this.fetchData()
      this.fetchHistory()
    },
    methods: {
      // 获取打卡记录
      fetchData() {
        this.loading = true
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          amStart: this.searchForm.startDate,
          pmEnd: this.searchForm.endDate
        }
        
        getClockList(params).then(response => {
          this.tableData = response.data.dataList
          this.pagination.total = response.data.total
          this.loading = false
          
          // 检查今天是否已打卡
          this.checkTodayClockStatus()
        }).catch(() => {
          this.loading = false
        })
      },
      
      // 获取统计信息
      fetchHistory() {
        getClockHistory().then(response => {
            console.log(response.data)
          this.stats = {
            normalDays: response.data.normalRecords || 0,
            lateTimes: response.data.lateRecords || 0,
            earlyTimes: response.data.earlyRecords || 0,
            absentDays: response.data.abnormalRecords || 0
          }
        })
      },
      
      // 处理打卡
      handleClockIn(type) {
        const loading = this.$loading({
          lock: true,
          text: '正在打卡...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        clockIn(type).then(response => {
          this.$message({
            message: `${type === 'am' ? '上班' : '下班'}打卡成功，状态：${response.data}`,
            type: 'success'
          })
          this.fetchData()
          this.fetchHistory()
        }).finally(() => {
          loading.close()
        })
      },
      
      // 检查今天是否已打卡
      checkTodayClockStatus() {
        const today = new Date().toISOString().split('T')[0]
        const todayRecord = this.tableData.find(item => {
          const amDate = item.am ? item.am.split(' ')[0] : ''
          const pmDate = item.pm ? item.pm.split(' ')[0] : ''
          return amDate === today || pmDate === today
        })
        
        if (todayRecord) {
          this.hasClockedInAM = !!todayRecord.am
          this.hasClockedInPM = !!todayRecord.pm
        }
      },
      
      // 搜索
      handleSearch() {
        this.pagination.currentPage = 1
        this.fetchData()
      },
      
      // 重置搜索
      handleReset() {
        this.searchForm = {
          startDate: '',
          endDate: ''
        }
        this.handleSearch()
      },
      
      // 分页大小改变
      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.fetchData()
      },
      
      // 当前页改变
      handleCurrentChange(val) {
        this.pagination.currentPage = val
        this.fetchData()
      },
      
      // 获取状态标签类型
      getStatusTagType(status) {
        switch (status) {
          case '正常': return 'success'
          case '迟到': return 'warning'
          case '早退': return 'danger'
          case '迟到且早退': return 'danger'
          default: return 'info'
        }
      }
    }
  }
  </script>
  
  <style scoped>
  .attendance-container {
    padding: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stat-item {
    text-align: center;
    padding: 10px;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .stat-label {
    font-size: 14px;
    color: #909399;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .search-form {
    display: flex;
    align-items: center;
  }
  
  .clock-buttons {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  </style>